package com.example.demo;

import org.noear.solon.net.annotation.ServerEndpoint;
import org.noear.solon.net.websocket.WebSocket;
import org.noear.solon.net.websocket.WebSocketListener;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.time.LocalDateTime;

@ServerEndpoint("/demo")
public class DemoWs implements WebSocketListener {

    @Override
    public void onOpen(WebSocket socket) {
        System.out.println("onOpen");
    }

    @Override
    public void onMessage(WebSocket socket, String text) throws IOException {
        socket.send(text);
        System.out.println("onMessage: " + text);
    }

    @Override
    public void onMessage(WebSocket socket, ByteBuffer binary) throws IOException {
        System.out.println("onMessage: " + binary);
        socket.send(ByteBuffer.wrap(LocalDateTime.now().toString().getBytes()));
    }

    @Override
    public void onClose(WebSocket socket) {
        System.out.println("onClose");
    }

    @Override
    public void onError(WebSocket socket, Throwable error) {
        error.printStackTrace();
    }

    @Override
    public void onPing(WebSocket socket) {
        socket.send("pong");
    }

    @Override
    public void onPong(WebSocket socket) {
        System.out.println("onPong");
    }
}